import os
import random
import hashlib
import time
import requests
from qiniu import Auth, put_data, BucketManager


# 上传图片
def upload_qiniu(filestorage):
    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'vkzLQY0awm-alBKeaMyATEbtSQGJhteVHqCC4tnT'
    secret_key = '_elDU1gkxSf0uHxl8HT34_knGDd2vLxQcyoWgIGs'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'flaskblog2020'
    # 上传后保存的文件名
    filename = filestorage.filename
    name, suffix = os.path.splitext(filename)
    key = filename + '_' + str(random.randint(1, 1000)) + suffix
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # # 要上传文件的本地路径
    # localfile = './sync/bbb.jpg'
    # ret, info = put_file(token, key, localfile)
    ret, info = put_data(token, key, filestorage.read())
    print(info)
    return ret, info

# 删除图片
def delete_qiniu(filename):
    access_key = 'vkzLQY0awm-alBKeaMyATEbtSQGJhteVHqCC4tnT'
    secret_key = '_elDU1gkxSf0uHxl8HT34_knGDd2vLxQcyoWgIGs'
    # 初始化Auth状态
    q = Auth(access_key, secret_key)
    # 初始化BucketManager
    bucket = BucketManager(q)
    # 你要测试的空间， 并且这个key在你空间中存在
    bucket_name = 'flaskblog2020'
    # key = 'python-logo.png'
    key = filename
    # 删除bucket_name 中的文件 key
    ret, info = bucket.delete(bucket_name, key)
    return info


# 发送短信
def send_message(mobile):
    url = 'https://api.netease.im/sms/sendcode.action'
    """
    AppKey	开发者平台分配的appkey
    Nonce	随机数（最大长度128个字符）
    CurTime	当前UTC时间戳，从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
    CheckSum	SHA1(AppSecret + Nonce + CurTime)，三个参数拼接的字符串，进行SHA1哈希计算，转化成16进制字符(String，小写)
    """
    appkey = "e43f7b8886f59d58d7861a31ba4c1dca"
    # 生成128个长度以内的随机字符串
    nonce = hashlib.new('sha512', str(time.time()).encode("utf-8")).hexdigest()
    # 获取当前时间戳
    curtime = str(int(time.time()))
    # 网易云信的 App Secret
    serct = "171dc0c8c491"
    # 根据要求进行SHA1哈希计算
    check_sum = hashlib.sha1((serct + nonce + curtime).encode("utf-8")).hexdigest()

    print(nonce, "\n", len(nonce))
    print(curtime)
    print(check_sum)

    header = {
        "AppKey": appkey,
        "Nonce": nonce,
        "CurTime": curtime,
        "CheckSum": check_sum
    }

    data = {
        'mobile': mobile,  # 你的手机号码
        'codeLen': '6'
    }

    resp = requests.post(url, data=data, headers=header)
    result = resp.json()
    print("Response:", result)
    return result